package com.fcy.teamwork.business.main.homepage.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.android.api.callback.GetUserInfoCallback
import cn.jpush.im.android.api.model.Conversation
import cn.jpush.im.android.api.model.UserInfo
import com.bumptech.glide.Glide
import com.fcy.teamwork.R
import com.fcy.teamwork.base.BaseActivity
import com.fcy.teamwork.base.toActivity
import com.fcy.teamwork.bean.Contact
import com.fcy.teamwork.bean.toContact
import com.fcy.teamwork.databinding.HomepageItemMessageBinding
import okhttp3.internal.notify
import java.util.Collections

typealias ItemListener = (Contact) -> Unit

class MessageListAdapter : RecyclerView.Adapter<MessageListAdapter.VH>() {
    private var source: List<Contact> = listOf()
    var onItemClick: ItemListener = {}

    inner class VH(
        private val binding: HomepageItemMessageBinding,
        val onClickAction: ItemListener
    ) :
        RecyclerView.ViewHolder(binding.root) {
        fun initData(contact: Contact) {
            Glide.with(binding.root).load(contact.portraitFile).placeholder(R.drawable.por2)
                .into(binding.ivPortrait)
            binding.tvTitle.text = contact.nickName
            binding.root.setOnClickListener {
                onClickAction(contact)
            }
            if (contact.hasUnRead) {
                binding.ivHasUnRead.visibility = View.VISIBLE
            } else {
                binding.ivHasUnRead.visibility = View.GONE
            }
            binding.root.setOnLongClickListener { _ ->
                if (!JMessageClient.deleteSingleConversation(contact.identify))
                    JMessageClient.deleteGroupConversation(contact.identify.toLong())
                val indexOf = source.indexOf(contact)
                source = ArrayList(source).apply {
                    removeAt(indexOf)
                }
                notifyItemRemoved(indexOf)
                return@setOnLongClickListener true
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun submitData(data: List<Contact>) {
        source = data
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val layoutInflater = LayoutInflater.from(parent.context)
        // RecyclerView 不绑定parent会导致item大小出现异常（item的布局只能是wrapContent不管怎么设置）
        val binding = HomepageItemMessageBinding.inflate(layoutInflater, parent, false)
        return VH(binding, onItemClick)
    }

    override fun onBindViewHolder(holder: VH, position: Int) {
        holder.initData(source[position])
    }

    override fun getItemCount(): Int = source.size

    fun modifyState(target: String, defaultState: Boolean = true) {
        val index = source.indexOfFirst { contact -> contact.identify == target }
        if (index !in source.indices) {
            val contact = (Conversation.createSingleConversation(target)
                ?: Conversation.createGroupConversation(target.toLong())).toContact()
            source = ArrayList(source).apply { add(contact) }
            notifyItemInserted(source.size - 1)
            return
        }
        source[index].hasUnRead = defaultState
        notifyItemChanged(index)
    }
}